package tjs.styudy.mini.springboot.devtools.fileWatch;

import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.io.File;

/**
 * Created by Nicky.Tang on 2021/9/29 11:52 下午
 *
 * @since 02.12.10
 */
public class FileSystemWatcher implements InitializingBean, ApplicationContextAware {
    private ApplicationContext applicationContext;

    private String initialUrls;

    public FileSystemWatcher(String initialUrls) {
        this.initialUrls = initialUrls;
    }

    public static void main(String[] args) {
        // FileSystemWatcher.start(null, null, 1000, "/Users/piangpiang/Documents/my-workspace/my-mayun/tjs-org/tjs-spring-loader/target/classes/tjs");
    }

    public void start(long interval, String path) {
        new Thread(() -> {
            this.doStart(interval, path);
        }).start();
    }

    private void doStart(long interval, String path) {
        try {
            FileAlterationObserver observer = new FileAlterationObserver(new File(path), (File pathname) -> {
                // 只监听class
                if (pathname.getPath().indexOf(".class") != -1 || pathname.isDirectory()) {
                    return true;
                }
                return false;
            });

            FileListenerAdaptor listener = new FileListenerAdaptor(this.applicationContext);
            observer.addListener(listener);
            FileAlterationMonitor fileMonitor = new FileAlterationMonitor(interval, new FileAlterationObserver[]{observer});

            //启动监听器
            fileMonitor.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        this.start(1000, this.initialUrls);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
